package stdio.costa.moca.rest;

import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.commons.codec.digest.DigestUtils;

import stdio.costa.moca.ThreadLocalSessionManager;
import stdio.costa.moca.model.Address;
import stdio.costa.moca.model.User;
import stdio.costa.moca.rest.exception.NotAuthorizedException;
import stdio.costa.moca.rest.exception.UserAlreadyExistException;

@Path("/user")
public class UserResource extends RestfulOperations {

	@Path("/login")
	@POST
	@Produces({ "application/json" })
	public User login(@FormParam("name") String name, @FormParam("password") String password) {
		logger.info("Trying login with user name:{}", name);
		User user = findUserByName(name);
		if (user == null || !isPasswordMatch(password, user)) {
			logger.info("The user: {} does not exist or the password does not match.", name);
			throw new NotAuthorizedException();
		}
		ThreadLocalSessionManager.setUser(user);
		return user;
	}

	@Path("/signup")
	@POST
	@Produces({ "application/json" })
	public User signup(@FormParam("name") String name, @FormParam("password") String password) {
		User user = findUserByName(name);
		if (user == null) {
			user = new User(name, DigestUtils.md5Hex(password));
			getEntityManager().persist(user);
			ThreadLocalSessionManager.setUser(user);
			return user;
		} else {
			throw new UserAlreadyExistException();
		}
	}

	@Path("/address")
	@POST
	@Produces({ "application/json" })
	public Address createAddress(@FormParam("addressUuid") String addressUuid, @FormParam("receiver") String receiver,
			@FormParam("postcode") String postcode, @FormParam("province") String province, @FormParam("city") String city,
			@FormParam("district") String district, @FormParam("addressLine1") String addressLine1,
			@FormParam("addressLine2") String addressLine2) {
		Address address = getEntityManager().find(Address.class, addressUuid);
		address.setReceiver(receiver);
		address.setPostcode(postcode);
		address.setProvince(province);
		address.setCity(city);
		address.setDistrict(district);
		address.setAddressLine1(addressLine1);
		address.setAddressLine2(addressLine2);
		getEntityManager().merge(address);
		return address;
	}
}
